package com.by.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.by.entity.Category;
import com.by.mapper.CategoryMapper;
import com.by.service.CategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品三级分类 服务实现类
 * </p>
 *
 * @author 黄佳辉
 * @since 2023-01-04
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Override
    public List<Category> getCategoryList() {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getParentId, 0);
        List<Category> categorysFirst = this.list(wrapper);

        for (Category item : categorysFirst) {
            this.getChildNodes(item);
        }
        return categorysFirst;
    }

    @Override
    public Boolean removeByIdWithChildren(Long id) {
        Category category = new Category();
        category.setId(id);
        List<Category> categoryList = new ArrayList<>();
        List<Category> childNodes = this.getAllChildNodes(categoryList, category);
        System.out.println(childNodes);
        Boolean removeFlag = this.removeBatchByIds(childNodes);
        return removeFlag;
    }

    //查找当前category的所有孩子并赋值
    public List<Category> getChildNodes(Category category) {

        Long parentId = category.getId();

        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getParentId, parentId);
        List<Category> categoryList = this.list(wrapper);

        if (null == categoryList || categoryList.size() == 0) return null;
        else{
            category.setChildNodes(categoryList);
            for (Category item : categoryList) {
                this.getChildNodes(item);
            }
        }
        return categoryList;
    }

    //收集当前category的所有孩子
    public List<Category> getAllChildNodes(List<Category> allChildNodes, Category category) {
        allChildNodes.add(category);

        Long parentId = category.getId();

        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getParentId, parentId);
        List<Category> categoryList = this.list(wrapper);

        if (null == categoryList || categoryList.size() == 0) return allChildNodes;
        else{
            for (Category item : categoryList) {
                this.getAllChildNodes(allChildNodes, item);
            }
        }
        return allChildNodes;
    }
}
